package com.ccx.coachsite.ui.login;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.RegisterBus;
import com.ccx.coachsite.bus.ReinfoBus;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.bus.GetVerifyCodeBus;
import com.ccx.coachsite.ui.login.LoginActivity.OnRegisterListener;
import com.ccx.coachsite.util.ContactsUtil;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.StringUtil;
import com.ccx.coachsite.util.CommonViewUtils;
import com.ccx.coachsite.webimage.HttpImage;
import com.ccx.coachsite.webimage.ImageLoader;
import com.ccx.coachsite.R;

public class RegisterActivity extends CommonActivity {

	public static final String IMAGE_UNSPECIFIED = "image/*";
	private static final int CAMERA_WITH_DATA = 3023;
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	private File mCurrentPhotoFile;

	Animation shake;
	private EditText mUserName; // 用户名
	private EditText mPassword; // 密码
	private EditText mRePassword; // 确认密码
	// private EditText mEmial; // 邮箱
	private EditText mMobile; // 手机号
	private EditText mVerityCode; // 验证码
	private Button btnSetPhoto;
	private ImageView imageHead;

	private View mReturn; // 返回
	private View mSave; // 保存
	private View mVerifyBtn; // 获取验证

	private Account account;
	private String fileName;
	private String mobileStr;
	boolean isModify;
	private int modifytype;

	private int loginType;
	private String weiboId;
	private String weiboTitle;
	private String weiboName;
	private String weiboHeader;

	@Override
	public void initComponents() {
		loginType = -1;
		mUserName = (EditText) findViewById(R.id.register_username);
		mPassword = (EditText) findViewById(R.id.register_password);
		mRePassword = (EditText) findViewById(R.id.register_password_again);
		// mEmial = (EditText) findViewById(R.id.register_email);
		mMobile = (EditText) findViewById(R.id.getphonenumber_mobile);
		mVerityCode = (EditText) findViewById(R.id.getphonenumber_verify_code);
		mVerifyBtn = findViewById(R.id.getphonenumber_btn_verify);
		mSave = findViewById(R.id.login_top_right);
		mSave.setOnClickListener(new OnRegister());
		mVerifyBtn.setOnClickListener(new OnGetVerify());
		mReturn = findViewById(R.id.login_btn_return);
		mReturn.setOnClickListener(new OnReturnClickListener());

		btnSetPhoto = (Button) findViewById(R.id.btn_regist_set_photo);
		btnSetPhoto.setOnClickListener(btnSetPhotoClickListener);
		imageHead = (ImageView) findViewById(R.id.register_head);

		/*
		 * mMobile.setText("18050407681"); mUserName.setText("189");
		 * mPassword.setText("18911111111"); mRePassword.setText("18911111111");
		 * mVerityCode.setText("");
		 */
		account = AccountMgr.readAccountInfo(mContext);
		Intent receiver = this.getIntent();
		modifytype = receiver.getIntExtra("modifytype", 0);
		if (modifytype == 1) {
			isModify = true;
			modifyType();
		} else if (modifytype == 2) {
			modifyWeibo(receiver);
		} else if (modifytype == 3) {
			modifyTianyi(receiver);
		}
	}

	public void modifyTianyi(Intent receiver) {
		loginType = receiver.getIntExtra("loginType", 0);
		mobileStr = receiver.getStringExtra("mobile");
		mMobile.setText(mobileStr);
		mMobile.setEnabled(false);
		mMobile.setFocusable(false);
		mUserName.forceLayout();
		View panelView = findViewById(R.id.register_code_panel);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_4);
		panelView.setVisibility(View.GONE);

	}

	public void modifyWeibo(Intent receiver) {
		mPassword.setText("111111");
		mRePassword.setText("111111");

		loginType = receiver.getIntExtra("loginType", 0);
		weiboId = receiver.getStringExtra("weiboId");
		weiboTitle = receiver.getStringExtra("weiboTitle");
		weiboName = receiver.getStringExtra("weiboName");
		weiboHeader = receiver.getStringExtra("weiboHeader");

		View panelView = findViewById(R.id.register_password_panel);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_repassword_panel);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_3);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_2);
		panelView.setVisibility(View.GONE);

		String picturePath = weiboHeader;
		imageHead.setImageResource(R.drawable.ower_image_none);
		if (picturePath != null) {
			imageHead.setImageResource(R.drawable.ower_image_none);
			ImageLoader.loadBitmap(picturePath, imageHead);
		}

		mUserName.setText(weiboName);
	}

	public void modifyType() {
		//account = AccountMgr.readAccountInfo(mContext);
		mPassword.setText(account.getQq());
		mRePassword.setText("111111");
		mVerityCode.setText("111111");
		mMobile.setText(account.getMobile());
		mUserName.setText(account.getUsername());

		String picturePath = account.getOwerIcon();
		imageHead.setImageResource(R.drawable.ower_image_none);
		if (picturePath != null) {
			imageHead.setImageResource(R.drawable.ower_image_none);
			ImageLoader.loadBitmap(picturePath, imageHead);
		}

		View panelView = findViewById(R.id.register_phone_panel);
		panelView.setVisibility(View.GONE);

		TextView passwordView = (TextView)findViewById(R.id.register_password);
		passwordView.setHint("QQ号码");
		passwordView.setInputType(InputType.TYPE_CLASS_PHONE);

		panelView = findViewById(R.id.register_repassword_panel);
		panelView.setVisibility(View.GONE);

		//panelView = findViewById(R.id.register_name_panel);
		//panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_code_panel);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_4);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_3);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_2);
		//panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_image_line_2);
		//panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.btn_regist_sumbit);
		panelView.setVisibility(View.VISIBLE);

		panelView = findViewById(R.id.register_username_title);
		panelView.setVisibility(View.GONE);

		panelView = findViewById(R.id.register_photo_title);
		panelView.setVisibility(View.VISIBLE);

		View modifyBut = findViewById(R.id.register_submit_btn);
		modifyBut.setOnClickListener(new OnModifyListener());
	}
	
	public void afterSuccess()
	{
		fileName = "";
	}

	class OnModifyListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (shake == null)
				shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);
			
			final String username = mUserName.getText().toString().trim();
			String qq = mPassword.getText().toString().trim();
			String sqq = account.getQq();
			if(StringUtil.isEmpty(qq))
				qq = "";
			if(StringUtil.isEmpty(sqq))
				sqq = "";
			
			
			
			if (StringUtil.isEmpty(username)) {
				CommonViewUtils
						.showErrorByEditText(mUserName, "用户名不能为空", shake);
				return;
			}
			else {
				if (username.indexOf("%") > 0) {
					CommonViewUtils.showErrorByEditText(mUserName,
							"用户名不能包含%符号", shake);
					return;
				}

			}
			
			if (!CommonViewUtils.isNetConnectionAvailable(mContext)) {
				Toast.makeText(mContext, "提交失败，请检查网络连接。",
						Toast.LENGTH_SHORT).show();
				return;

			}
			
			String tmp = account.getUsername();
			if(StringUtil.isEmpty(fileName) && (!StringUtil.isEmpty(username) && username.equals(tmp))
					&& qq.equals(sqq))
			{
				Toast.makeText(mContext, "未修改任何信息", Toast.LENGTH_SHORT).show();
				return;
			}
			
			account.setUsername(username);
			account.setQq(qq);
			
			// account.setOwerIcon(fileName);

			ReinfoBus bo = new ReinfoBus(RegisterActivity.this);
			bo.changeInfo(account, fileName);
		}
	}

	class OnGetVerify implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (shake == null)
				shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);

			String mobilenumber = mMobile.getText().toString().trim();
			if (StringUtil.isEmpty(mobilenumber)) {
				CommonViewUtils.showErrorByEditText(mMobile,
						getString(R.string.register_mobile_empty), shake);
				return;
			}
			if (!StringUtil.isMobile(mobilenumber)) {
				CommonViewUtils.showErrorByEditText(mMobile,
						getString(R.string.register_mobile_error), shake);
				return;
			}
			if (!CommonViewUtils.isNetConnectionAvailable(mContext)) {
				Toast.makeText(mContext, R.string.login_network_error,
						Toast.LENGTH_SHORT).show();
				return;
			}

			GetVerifyCodeBus bo = new GetVerifyCodeBus(RegisterActivity.this);
			bo.getVerifyCode(mobilenumber);
		}
	}

	class OnRegister implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (shake == null)
				shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);

			final String username = mUserName.getText().toString().trim();
			final String password = mPassword.getText().toString().trim();
			final String repassword = mRePassword.getText().toString().trim();
			final String verifyCode = mVerityCode.getText().toString().trim();
			final String mobile = mMobile.getText().toString().trim();

			if (StringUtil.isEmpty(mobile)) {
				CommonViewUtils.showErrorByEditText(mMobile,
						getString(R.string.register_mobile_empty), shake);
				return;
			}
			
			if (!ContactsUtil.checkContact(mobile)) {
				CommonViewUtils.showErrorByEditText(mMobile,
						"请输入天翼手机号码", shake);
				return;
			}

			if (modifytype != 3 && StringUtil.isEmpty(verifyCode)) {
				CommonViewUtils.showErrorByEditText(mVerityCode,
						getString(R.string.register_verify_code_empty), shake);
				return;
			}

			if (StringUtil.isEmpty(password)) {
				CommonViewUtils.showErrorByEditText(mPassword,
						getString(R.string.register_password_empty), shake);
				return;
			}

			if (!StringUtil.isPwdValid(password)) {
				CommonViewUtils.showErrorByEditText(mPassword,
						getString(R.string.register_password_valid), shake);
				return;
			}

			if (StringUtil.isEmpty(repassword)) {
				CommonViewUtils.showErrorByEditText(mRePassword,
						getString(R.string.register_password_empty), shake);
				return;
			}

			if (!password.equals(repassword)) {
				CommonViewUtils.showErrorByEditText(mRePassword,
						getString(R.string.register_password_not_equal), shake);
				return;
			}

			if (StringUtil.isEmpty(username)) {
				account.setUsername(mobile);
			} 
			else {
				
				if (username.indexOf("%") > 0) {
					CommonViewUtils.showErrorByEditText(mUserName,
							"用户名不能包含%符号", shake);
					return;
				}

				account.setUsername(username);
			}

			String imsi = "imsi";// AppHelper.getMobileIMSI(mContext);

			account.setPassword(password);
			account.setMVerifyCode(verifyCode);
			account.setImsi(imsi);
			account.setMobile(mobile);
			account.setOwerIcon(fileName);
			account.setWeiboId(weiboId);
			account.setWeiboType(loginType);
			account.setWeiboName(weiboName);
			if (StringUtil.isEmpty(fileName) && loginType >= 1
					&& !StringUtil.isEmpty(weiboHeader)) {
				String file = HttpImage.getFilePath(weiboHeader);
				if (FileUtil.isFileExits(file)) {
					String imageName = HttpImage.SDCARD_IMAGE_CACHE_DIR
							+ "tmp_regist.jpg";
					Bitmap bit = BitmapFactory.decodeFile(file);
					try {
						FileOutputStream out = new FileOutputStream(imageName);
						bit.compress(Bitmap.CompressFormat.JPEG, 90, out);

						fileName = imageName;
						account.setOwerIcon(fileName);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}
			/*
			 * if(mCurrentPhotoFile != null)
			 * account.setOwerIcon(mCurrentPhotoFile.getAbsolutePath()); if
			 * (!CommonViewUtils.isNetConnectionAvailable(mContext)) {
			 * Toast.makeText(mContext, R.string.login_network_error,
			 * Toast.LENGTH_SHORT).show(); return; }
			 */
			RegisterBus bo = new RegisterBus(RegisterActivity.this);
			bo.setParams(account);
			bo.register();
		}
	}

	@Override
	protected int getMainContentViewId() {
		return R.layout.register_activity;
	}

	@Override
	protected Class<?> getResouceClass() {
		return R.class;
	}

	@Override
	protected void setCustomTitleTop() {
		View v = findViewById(R.id.login_top_right);
		if (isModify) {
			TopViewUtil.updateTitle(this, R.id.login_top_title, "个人资料");
			
			if(v != null)
				v.setVisibility(View.INVISIBLE);
			//TopViewUtil.setRightVisable(this, R.id.login_top_right, View.INVISIBLE);
		} else {
			TopViewUtil.updateTitle(this, R.id.login_top_title,
					getString(R.string.register));
			TopViewUtil.updateRightTitle(this, R.id.login_top_right,
					R.string.register_save);
			TopViewUtil.updateRight(this, R.id.login_top_right,
					R.drawable.login_save_btn);
			if(v != null)
				v.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void initData() {
		//account = AccountMgr.readAccountInfo(mContext);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
			Bitmap photo = data.getParcelableExtra("data");
			imageHead.setImageBitmap(photo);

			savePhoto(photo);

			break;
		}
		case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			startPhotoZoom(mCurrentPhotoFile);
			break;
		}
		}
	}
	
	private void savePhoto(Bitmap photo)
	{
		String dir = HttpImage.SDCARD_IMAGE_DIR;
		fileName = dir + "/"
				+ getPhotoFileName();

		try {
			FileOutputStream out = new FileOutputStream(fileName);
			photo.compress(Bitmap.CompressFormat.JPEG, 90, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void startPhotoZoom(File f) {
		/*
		try {
			Bitmap originalPhoto = BitmapFactory.decodeFile(f.getPath());
			Bitmap photo = Bitmap.createScaledBitmap(originalPhoto, 90, 90,
					true);
			imageHead.setImageBitmap(photo);
			savePhoto(photo);
			originalPhoto.recycle();
		} catch (Exception e1) {
			Log.e(e1.getMessage());
		}
		*/
		
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(Uri.fromFile(f), IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 90);
			intent.putExtra("outputY", 90);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Log.e(e.getMessage());
			try {
				Bitmap originalPhoto = BitmapFactory.decodeFile(f.getPath());
				Bitmap photo = Bitmap.createScaledBitmap(originalPhoto, 90, 90,
						true);
				imageHead.setImageBitmap(photo);
				savePhoto(photo);
				originalPhoto.recycle();
			} catch (Exception e1) {
				Log.e(e1.getMessage());
			}
			Toast.makeText(this, "对不起，无法启动图片编辑", Toast.LENGTH_LONG).show();
		}
		
	}

	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		return "IMG" + dateFormat.format(date) + ".jpg";
	}

	OnClickListener btnSetPhotoClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				Toast.makeText(RegisterActivity.this, "对不起，请先接入 SD卡",
						Toast.LENGTH_SHORT).show();
				return;
			}
			new AlertDialog.Builder(RegisterActivity.this).setItems(
					new String[] { "相机", "图库" },
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								doTakePhoto();
							} else {
								doPickPhotoFromGallery();
							}
						}
					}).show();
		}
	};

	protected void doTakePhoto() {
		try {
			//Environment.getExternalStorageDirectory()
			String dir = HttpImage.SDCARD_IMAGE_DIR;
			mCurrentPhotoFile = new File(
					dir,
					getPhotoFileName());
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "无法启动摄像机", Toast.LENGTH_LONG).show();
		}
	}

	protected void doPickPhotoFromGallery() {
		try {
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "对不起，找不到图库", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 90);
		intent.putExtra("outputY", 90);
		intent.putExtra("return-data", true);
		return intent;
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}
}
